package com.vf.editor.mvc.resources.model;

import java.io.File;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.vf.editor.common.controller.BaseController;
import com.vf.editor.common.model.resources.Model;
import com.vf.editor.common.model.resources.ModelClassify;
import com.vf.editor.common.util.FileUtil;
import com.vf.editor.common.util.UuidUtil;
import com.vf.editor.common.util.ZipUtil;

@Path(value = "/resources/model", viewPath = "/views/resources/model/")
public class ModelController extends BaseController{
	
	public void index() {
		this.render("list.html");
	}
	
	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");
		String classifyId = getPara("classifyId");

		String sqlExceptSelect = " FROM " + Model.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keyword + "%'  ) ";
		}
		if (!StrKit.isBlank(classifyId)) {
			sqlExceptSelect += " AND O.CLASSIFYID = '" + classifyId + "'   ";
		}
		sqlExceptSelect += "  ORDER BY   O.CREATETIME DESC ";
		Page<Model> page = Model.dao.paginate(pageNumber, pageSize, "select * ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	
	public void save() {
		Model model = getModel(Model.class);
		if (StrKit.notBlank(model.getId())) {
			if (model.update()) {
				renderSuccess("更新成功！",model);
			} else {
				renderError("更新失败！");
			}
		} else {
			model.setId(UuidUtil.getUUID());
			String classifyIdId;
			if(StrKit.isBlank(model.getClassifyId())) {
				classifyIdId="1";
				model.setClassifyId(classifyIdId);
			}else {
				classifyIdId=model.getClassifyId();
			}
			ModelClassify modelClassify=ModelClassify.dao.findById(classifyIdId);
			if (model.save()) {
				try {
					if(modelClassify!=null) {
						modelClassify.setCount(modelClassify.getCount()+1);
						modelClassify.update();
					}
				}catch (Exception e) {
				}
				renderSuccess("保存成功！",model);
			} else {
				renderError("保存失败！");
			}
		}
	}
	
	@Before(Tx.class)
	public void delete() throws Exception {
		String id = getPara("id");
		Model model = Model.dao.findById(id);
		if (model != null) {
			if (model.delete()) {
				renderSuccess("删除成功！",model);
				FileUtil.deleteFolder(rootPath+"/upload/model/"+model.getId()+"/");
				try {
					ModelClassify modelClassify=ModelClassify.dao.findById(model.getClassifyId());
					if(modelClassify!=null) {
						modelClassify.setCount(modelClassify.getCount()-1);
						modelClassify.update();
					}
				}catch (Exception e) {
				}
				
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
	public void getById() {
		String id = getPara("id");
		Model model = Model.dao.findById(id);
		if (model != null) {
			renderSuccess("成功！",model);
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
	private String rootPath = PathKit.getWebRootPath();
	public void upload() {
		UploadFile uploadFile = getFile();
		try {
			String classifyId=getPara("classifyId","1");
			ModelClassify modelClassify=ModelClassify.dao.findById(classifyId);
			if(modelClassify==null) {
				renderError("无效分组，请检查是否存在!");
				return ;
			}
			String modelId=UuidUtil.getUUID();
			String path = "/upload/model/"+modelId + "/" + uploadFile.getFileName().replace(" ", "");
			File file = new File(rootPath+path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (file.exists()) {
				file.delete();
			}
			if(uploadFile.getFile().renameTo(file)) {
				String suffix=FileUtil.lastName(file);
				Model bizModel = new Model();
				if(StrKit.equals("zip",suffix)) {
					List<String> list=ZipUtil.unZip(file, rootPath+"/upload/model/"+modelId + "/");
					if (file.exists()) {
						file.delete();
					}
					if(list!=null && list.size()>0) {
						for (String string : list) {
							if(string.contains(".gltf")||string.contains(".glb")) {
								bizModel.setType("2");
								bizModel.setUrl("/upload/model/"+modelId + "/"+string);
								break;
							}
							else if(string.contains("tileset.json")) {
								bizModel.setType("1");
								bizModel.setUrl("/upload/model/"+modelId + "/"+string);
								break;
							}
						}
						if(StrKit.isBlank(bizModel.getType())) {
							FileUtil.deleteFolder(rootPath+"/upload/model/"+modelId+"/");
							throw new Exception("格式有误，上传失败！");
						}
					}else {
						FileUtil.deleteFolder(rootPath+"/upload/model/"+modelId+"/");
						throw new Exception("格式有误，上传失败！");
					}
				}else {
					if(!(suffix.contains("gltf")||suffix.contains("glb"))) {
						FileUtil.deleteFolder(rootPath+"/upload/model/"+modelId+"/");
						throw new Exception("格式有误，上传失败！");
					}
					bizModel.setType("2");
					bizModel.setUrl(path);
				}
				
				bizModel.setId(modelId);
				bizModel.setName(FileUtil.getFileNameWithoutSuffix(file));
				bizModel.setClassifyId(classifyId);
				bizModel.setIsRelative("1");
				if(bizModel.save()) {
					try {
						modelClassify.setCount(modelClassify.getCount()+1);
						modelClassify.update();
					}catch (Exception e) {
					}
					renderSuccess("上传成功！");
				}else {
					FileUtil.deleteFolder(rootPath+"/upload/model/"+modelId+"/");
					throw new Exception("上传失败！");
				}
			}else {
				FileUtil.deleteFolder(rootPath+"/upload/model/"+modelId+"/");
				throw new Exception("上传失败！");
			}
		} catch (Exception e) {
			renderError(e.getMessage());
		}
	}

	public void uploadThumbnail() {
		UploadFile uploadFile = getFile();
		try {
			String id=this.getPara("id");

			if(StrKit.isBlank(id)) {
				renderError("参数必填！");
				return;
			}
			
			Model model = Model.dao.findById(id);
			if(model==null) {
				renderError("参数无效！");
				return;
			}
			String thumbnail = "/upload/model/"+id+ "/" + uploadFile.getFileName().replace(" ", "");
			File file = new File(rootPath+thumbnail);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (file.exists()) {
				file.delete();
			}
			model.setThumbnail(thumbnail);
			if(uploadFile.getFile().renameTo(file)) {
				model.update();
				renderSuccess("成功！",model);
			}else {
				renderError("失败！");
			}
		} catch (Exception e) {
			renderError(e.getMessage());
		}
	}
	
	public void saveClassify() {
		ModelClassify model = getModel(ModelClassify.class);
		if (StrKit.notBlank(model.getId()) ) {
			if (model.update()) {
				renderSuccess("更新成功！",model);
			} else {
				renderError("更新失败！");
			}
		} else {
			model.setId(UuidUtil.getUUID());
			if (model.save()) {
				renderSuccess("保存成功！",model);
			} else {
				renderError("保存失败！");
			}
		}
	}
	
	public void getClassifys() {
		List<ModelClassify> classifies=ModelClassify.dao.find("SELECT * FROM "+ModelClassify.TABLE_NAME+" ORDER BY SORT ASC ");
		if (classifies!=null) {
			renderSuccess("成功！",classifies);
		} else {
			renderError("暂无分类！");
		}
	}
	
	
	public void listDataForClassify() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");
		String sqlExceptSelect = " FROM " + ModelClassify.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keyword + "%'  ) ";
		}
		sqlExceptSelect += "  ORDER BY   O.SORT ASC ";
		Page<ModelClassify> page = ModelClassify.dao.paginate(pageNumber, pageSize, "select * ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	
	
	
	@Before(Tx.class)
	public void deleteClassify() throws Exception {
		String id = getPara("id");
		ModelClassify model = ModelClassify.dao.findById(id);
		if (model != null) {
			if (model.delete()) {
				renderSuccess("删除成功！",model);
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
}
